﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;

namespace ShanghaiMetroAPP.MetroDraw
{
    /// <summary>
    /// 线路信息，绘制线路的功能也应在此
    /// </summary>
    public class Line
    {
        private static List<Line> _instance;// = new List<Line>();
        /// <summary>
        /// 这个方法线程不安全!
        /// </summary>
        /// <returns></returns>
        public static List<Line> GetInstance()
        {
            if(_instance == null)
            {
                //从文件中读取线路配置
                var json = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "TestingData\\LineInfo.json");
                var arr = JArray.Parse(json);
                //_instance = arr.ToObject<List<Line>>();
                var lines = new List<Line>();
                //手动读取配置文件
                foreach(var element in arr)
                {
                    var line = new Line();

                    if(element["line_no"] != null)
                    {
                        line.LineNo = element["line_no"].Value<int>();
                    }
                    if(element["color"] != null)
                    {
                        var colorNode = element["color"];
                        var color = Color.FromRgb(
                            colorNode["r"].Value<byte>(), 
                            colorNode["g"].Value<byte>(), 
                            colorNode["b"].Value<byte>());
                        line.Color = color;
                    }

                    lines.Add(line);
                }
                _instance = lines;
            }
            return _instance;
        }
        /// <summary>
        /// 获取指定线路号的Line实例，如果配置文件中没有配置该线路，则返回null
        /// </summary>
        /// <param name="lineNo"></param>
        /// <returns></returns>
        public static Line GetInstance(int lineNo)
        {
            foreach(var line in GetInstance())
            {
                if (line.LineNo == lineNo)
                    return line;
            }
            return null;
        }
        [JsonProperty("line_no")]
        public int LineNo { get; set; }
        [JsonProperty("color")]
        public Color Color { get; set; }
    }
}
